from . import user_blueprint
from ..exts import db
from ..models import *
from flask import Flask,request,make_response,render_template
import json
import random
from werkzeug.security import generate_password_hash,check_password_hash


@user_blueprint.route('/hello_user')
def hello_user_views():
    return "user蓝图测试"

@user_blueprint.route('/personal-re.html',methods=['POST','GET'])
def personalreg_views():
    if request.method == 'GET':
        return render_template('personal-re.html')
    else:
        userinfo = request.form

        uname = userinfo['username']
        uphnum = userinfo['phonenum']

        upwd = userinfo['confirm-passwd']
        trans_pwd = userinfo['trans-pwd']

        upwd = generate_password_hash(upwd)
        trans_pwd = generate_password_hash(trans_pwd)

        user = User()
        user.uname = uname
        user.upwd = upwd
        user.uphnum = uphnum
        user.trans_pwd = trans_pwd

        try:
            db.session.add(user)
            db.session.commit()
            return "注册成功"
        except Exception:
            return "注册失败"


# 验证用户名是否存在 
@user_blueprint.route('/test-username')
def testname_views():
    # 接受前端传递过来的数据
    uname = request.args['uname']
    # uphnum = request.args['uphnum']
    users = User.query.all()
    repname = ""
    for u in users:
        if uname == u.to_dict()['uname']:
            repname = uname
    result = {
        "uname":repname
    }
    return json.dumps(result)


# 验证手机号是否存在
@user_blueprint.route('/test-userph')
def testup_views():
    # 接受前端传递过来的数据
    uphnum = request.args['uphnum']
    users = User.query.all()
    repphnum = ""
    for u in users:
        if uphnum == u.to_dict()['uphnum']:
            repphnum = uphnum
    result = {
        "uphnum":repphnum
    }
    return json.dumps(result)

# 生成验证码返回
@user_blueprint.route('/check-message',methods=['GET','POST'])
def check_msg():
    ver = []
    for i in range(6):
        j = random.randint(0,9)
        ver.append(str(j))
    code = ''.join(ver)
    return code